package com.mikao.util;

import com.alibaba.fastjson.JSONObject;
import com.mikao.wxpay.WxPay;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URLDecoder;


public class JsapiTicketUtil {

    public static final Logger LOG = LoggerFactory.getLogger(JsapiTicketUtil.class);

    public static String getJsapiTicket() {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?";
        String params = "grant_type=client_credential&appid=" + WxPay.appid + "&secret=" + WxPay.secret + "";
        String result = httpGet(requestUrl + params);
        String access_token = JSONObject.parseObject(result).getString("access_token");
        requestUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?";
        params = "access_token=" + access_token + "&type=jsapi";
        result = httpGet(requestUrl + params);
        String jsapi_ticket = JSONObject.parseObject(result).getString("ticket");
        return jsapi_ticket;
    }

    /**
     * post请求
     *
     * @param url
     * @return
     */
    public static String httpPost(String url) {
        //post请求返回结果
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);
        String str = "";
        try {
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /**请求发送成功，并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {
                try {
                    /**读取服务器返回过来的json字符串数据**/
                    str = EntityUtils.toString(result.getEntity());
                } catch (Exception e) {
                    LOG.error("post请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            LOG.error("post请求提交失败:" + url, e);
        }
        return str;
    }

    /**
     * get 请求、
     *
     * @param url
     * @return
     */
    public static String httpGet(String url) {
        //get请求返回结果
        String strResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);

            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                strResult = EntityUtils.toString(response.getEntity());
            } else {
                LOG.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            LOG.error("get请求提交失败:" + url, e);
        }
        return strResult;
    }

}
